package org.star.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.star.enums.ResponseEnum;
import org.star.result.R;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * @Author : 一叶浮萍归大海
 * @Date: 2024/1/4 21:47
 * @Description: Spring Cloud Alibaba Sentinel统一异常处理
 */
@Slf4j
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.error("Spring Cloud Alibaba Sentinel error : {}",e.getRule());
        R r = null;
        if (e instanceof FlowException) {
            r = R.error(ResponseEnum.SENTINEL_FLOW_EXCEPTION.getCode(),ResponseEnum.SENTINEL_FLOW_EXCEPTION.getMessage());
        } else if (e instanceof DegradeException) {
            r = R.error(ResponseEnum.SENTINEL_DEGRADE_EXCEPTION.getCode(),ResponseEnum.SENTINEL_DEGRADE_EXCEPTION.getMessage());
        } else if (e instanceof ParamFlowException) {
            r = R.error(ResponseEnum.SENTINEL_PARAM_FLOW_EXCEPTION.getCode(),ResponseEnum.SENTINEL_PARAM_FLOW_EXCEPTION.getMessage());
        } else if (e instanceof SystemBlockException) {
            r = R.error(ResponseEnum.SENTINEL_SYSTEM_BLOCK_EXCEPTION.getCode(),ResponseEnum.SENTINEL_SYSTEM_BLOCK_EXCEPTION.getMessage());
        } else if (e instanceof AuthorityException) {
            r = R.error(ResponseEnum.SENTINEL_AUTHORITY_EXCEPTION.getCode(),ResponseEnum.SENTINEL_AUTHORITY_EXCEPTION.getMessage());
        } else {
            r = R.error();
        }

        response.setStatus(500);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(),r);
    }
}
